package com.ygxsk.carhome.ui.usercenter;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.jakewharton.rxbinding4.widget.RxTextView;
import com.jakewharton.rxbinding4.widget.TextViewAfterTextChangeEvent;
import com.tencent.mmkv.MMKV;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.home.HomeMainFragmentActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.KeyboardWatcher;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.nio.charset.Charset;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi
 * @Time:2019/12/21 0021  11:21
 * @Description: 提交修改密码的界面，修改完毕 应该直接跳转到登录页，乐软是这么做的。
 */
//public class ChangePasswordActivity extends ErrorActivity implements KeyboardWatcher.SoftKeyboardStateListener {
public class ChangePasswordActivity extends ErrorActivity {


    /*@BindView(R.id.layoutimagelogochange)
    ImageView layoutImageLogoChange;*/

    @BindView(R.id.bodychange)
    LinearLayout bodyChange;

    /**
     * 请输入旧密码
     */
    @BindView(R.id.etpasswordold)
    EditText etPasswordOld;//

    /**
     * 请输入新密码
     */
    @BindView(R.id.etnewpassword)
    EditText etPasswordNew;//

    /**
     * 再次确认新密码
     */
    @BindView(R.id.etnewpasswordconfirm)
    EditText etPasswordNewConfirm;//

    //确认修改密码按钮内容
    @BindView(R.id.btn_nextchange)
    RoundTextView btnNextChange;


    //第一种方式内容。
    private int screenHeight = 0;//屏幕高度
    private final float scale = 0.8f; //logo缩放比例
    private KeyboardWatcher keyboardWatcher;

    /**
     * 暂时是仅仅监听旧密码的输入和新密码是否符合规则
     */
    private final CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //设置全屏
        //ScreenUtils.setFullScreen(this);
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initViews();

//        apiSubSonListener = new ApiSubSonListener(ConstantApi.IS_ACTIVITY_ITSELF, ChangePasswordActivity.this);

//        initListener();

        //点击屏幕空白区域隐藏软键盘
        KeyboardUtils.clickBlankArea2HideSoftInput();

    }


    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        //toolbarygxskchange
        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @OnClick(R.id.btn_nextchange)
    public void clickInChangePassword(View view) {

        switch (view.getId()) {

            case R.id.btn_nextchange: {

                if (!DoubleClickListener.isFastDoubleClick()) {

                    KeyboardUtils.hideSoftInput(mActivityInstance);

                    String oldPassword = etPasswordOld.getText().toString().trim();

                    String newPassword = etPasswordNew.getText().toString().trim();

                    String newPasswordConfirm = etPasswordNewConfirm.getText().toString().trim();

                    if (TextUtils.isEmpty(oldPassword)) {
                        CommUtils.method_showAlertViewSingle(mActivityInstance, StringUtils.getString(R.string.clearaddorsubmitsuretitletips), getString(R.string.inputoldpsd), true);
                        return;
                    }

                    if (TextUtils.isEmpty(newPassword)) {
                        CommUtils.method_showAlertViewSingle(mActivityInstance, StringUtils.getString(R.string.clearaddorsubmitsuretitletips), getString(R.string.input_new_psw), true);
                        return;
                    }

                    //校验新密码是否符合规则
                    if (!methodCheckNewPassrod(newPassword)) {
                        //新密码输入：8-20位数字和字母组合~
                        CommUtils.method_showAlertViewSingle(mActivityInstance, StringUtils.getString(R.string.clearaddorsubmitsuretitletips), getString(R.string.input_psw_rules), true);
                        return;
                    }

                    if (TextUtils.isEmpty(newPasswordConfirm)) {
                        CommUtils.method_showAlertViewSingle(mActivityInstance, StringUtils.getString(R.string.clearaddorsubmitsuretitletips), getString(R.string.input_new_psw_confirm), true);
                        return;
                    }

                    //比较两次密码是否一致
                    if (!TextUtils.equals(newPassword, newPasswordConfirm)) {
                        CommUtils.method_showAlertViewSingle(mActivityInstance, StringUtils.getString(R.string.clearaddorsubmitsuretitletips), getString(R.string.input_two_psw_different), true);
                        return;
                    }

                    //EncodeUtils.base64Encode2String((EncryptUtils.encryptMD5ToString(oldsword)).getBytes(Charset.defaultCharset()))

                    HashMap<String, Object> jsonObject = new HashMap<>();
                    jsonObject.put(Parameterkey.oldPassword, EncodeUtils.base64Encode2String((EncryptUtils.encryptMD5ToString(oldPassword)).getBytes(Charset.defaultCharset())));//旧密码
                    jsonObject.put(Parameterkey.password, EncodeUtils.base64Encode2String((EncryptUtils.encryptMD5ToString(newPassword)).getBytes(Charset.defaultCharset())));//新密码
                    jsonObject.put(Parameterkey.password2, EncodeUtils.base64Encode2String((EncryptUtils.encryptMD5ToString(newPasswordConfirm)).getBytes(Charset.defaultCharset())));//再次输入的新密码

                    //jsonObject.put(ConstantApi.SHOPINFOID, mSession.getShopInfoId());
                    jsonObject.put(Parameterkey.communityId, mSession.getCommunityId());//communityId
                    //jsonObject.put("deviceToken", driviceTokenLocal);

                    AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
                    addLogUpLoadInfo.setActivity(mActivityInstance);
                    addLogUpLoadInfo.setWhat(ConstantApi.WHAT_CHANGEPASSWORD);//请求数字标识
                    addLogUpLoadInfo.setUrlPath(ApiService.updatePasswordUrl);//url地址
                    addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
                    addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
                    addLogUpLoadInfo.setHashMapParameter(jsonObject);

                    //做界面展示给用户的
                    NetworkManager.getInstance().initRetrofitRxJava()
                            .create(ApiService.class)
                            .updatePassword(RequestBody.create(JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                            .compose(ChangePasswordActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                            .compose(new ResponseTransformer<>(addLogUpLoadInfo,
                                    new ApiRequestSubListener<Boolean>(ConstantApi.IS_ACTIVITY_ITSELF, ChangePasswordActivity.this) {
                                        @Override
                                        public void onErrorServerNotSuccessDataResponse(int method, boolean isToastToUser, Activity _activity, String statusCode, String message) {
                                            super.onErrorServerNotSuccessDataResponse(method, isToastToUser, _activity, statusCode, message);
                                        }
                                    })).flatMap(new Function<Boolean, ObservableSource<Integer>>() {
                                @Override
                                public ObservableSource<Integer> apply(Boolean aBoolean) throws Throwable {

                                    //走到这里就算是执行成功了
                                    //String data = response.succeed().getData();
                                    ToastUtils.showShort(StringUtils.getString(R.string.changepsdsuccess));

                                    return Observable.just(1, 2, 3);
                                }
                            })
                            .subscribe(new Consumer<Integer>() {
                                @Override
                                public void accept(Integer integerValuePull) throws Exception {

                                    //参数和响应格式是
//                                    {
//                                            "communityId":"1",
//                                            "oldPassword":"RTEwQURDMzk0OUJBNTlBQkJFNTZFMDU3RjIwRjg4M0U=",
//                                            "password":"OTNBOUU1QkIxRDU5OEE0NTM2MDZFODkwRjcyQkQzOTM=",
//                                            "password2":"OTNBOUU1QkIxRDU5OEE0NTM2MDZFODkwRjcyQkQzOTM="
//                                    }
//                                    {
//                                            "code":"20000",
//                                            "data":true,
//                                            "message":"success"
//                                    }

                                    if (integerValuePull == 1) {

                                        //修改成功提示,并且跳转到登录页----成功之后才能杀死，不然过早杀死。
                                        //并且清空掉该项目之中管理的所有activity
                                        if (ActivityUtils.isActivityExistsInStack(SettingActivity.class)) {
                                            ActivityUtils.finishActivity(SettingActivity.class);
                                        }

                                        if (ActivityUtils.isActivityExistsInStack(HomeMainFragmentActivity.class)) {
                                            ActivityUtils.finishActivity(HomeMainFragmentActivity.class);
                                        }

                                    } else if (integerValuePull == 2) {

                                        //和退出登录逻辑相似
                                        CommUtils.loginOutClearData(mSession, MMKV.defaultMMKV().decodeString(ConstantSign.P_INPUTNAMELASTTIME));
                                        //CommUtils.displayToastShort(SettingActivity.this, "退出成功");

                                    } else if (integerValuePull == 3) {

                                        Bundle bundle = new Bundle();
                                        bundle.putInt(ExtraKey.EXTRA_REQUEST_20401, ExtraValue.RESPONSE_20401);
                                        //跳转到登录界面去重新登录。
                                        //这个也要走20401用户信息失效的逻辑.
                                        ActivityUtils.startActivity(bundle, LoginCarActivity.class);
                                        //清掉该界面
                                        methodBack();

                                    }

                                }
                                //自定义
                            }, new ErrorConsumer() {

                                @Override
                                protected void error(ApiException e) {

                                }
                            });

                }

                break;
            }

            default:
                break;
        }

    }

    @Override
    public Resources getResources() {
        return super.getResources();
    }

    private void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {//

        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_change_password;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_chanage_psw));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {
        //
    }

    @Override
    protected void initViews() {

        screenHeight = this.getResources().getDisplayMetrics().heightPixels; //获取屏幕高度
        //LogUtils.d("itchen--屏幕高度--" + screenHeight);

        if (ScreenUtils.getScreenWidth() > 1080) {
            btnNextChange.setTextSize(18);
        }

        //做一次旧密码校验。
        mCompositeDisposable.add(RxTextView.afterTextChangeEvents(etPasswordOld)//
                .debounce(2000, java.util.concurrent.TimeUnit.MILLISECONDS)//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<TextViewAfterTextChangeEvent>() {
                    @Override
                    public void accept(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Exception {

                        String oldPassWord = textViewAfterTextChangeEvent.getEditable().toString();

                        if (!TextUtils.isEmpty(oldPassWord)) {

                            //LogUtils.d("itchen---->获取到的旧密码=>" + oldPassWord);

                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put(Parameterkey.password, EncodeUtils.base64Encode2String((EncryptUtils.encryptMD5ToString(oldPassWord)).getBytes(Charset.defaultCharset())));

                            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
                            addLogUpLoadInfo.setActivity(mActivityInstance);
                            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_VALIDATEPASSWORD);//请求数字标识
                            addLogUpLoadInfo.setUrlPath(ApiService.validatePasswordUrl);//url地址
                            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
                            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
                            addLogUpLoadInfo.setHashMapParameter(hashMap);

                            //做界面展示给用户的
                            NetworkManager.getInstance().initRetrofitRxJava()
                                    .create(ApiService.class)
                                    .validatePassword(RequestBody.create(JSON.toJSONString(hashMap, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),//
                                            MediaType.parse(ApiService.HEADER_JSON)))
                                    .compose(ChangePasswordActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                                    .compose(new ResponseTransformer<>(addLogUpLoadInfo,//
                                            new ApiRequestSubListener<Boolean>(ConstantApi.IS_ACTIVITY_ITSELF, ChangePasswordActivity.this) {//

                                                @Override
                                                public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                                                    super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                                                    //如果校验原始密码有异常 就提示异常，没有异常就不提示
                                                    if (!TextUtils.isEmpty(serverMessage)) {
                                                        CommUtils.method_showAlertViewSingle(ChangePasswordActivity.this,//
                                                                ConstantSign.ALERT_TITLE, serverMessage, true);//
                                                    } else {
                                                        CommUtils.method_showAlertViewSingle(ChangePasswordActivity.this,//
                                                                ConstantSign.ALERT_TITLE, getString(R.string.compareoldpsdabnomal), true);//
                                                    }

                                                }


                                            }))
                                    .subscribe(new Consumer<Boolean>() {//
                                        @Override
                                        public void accept(Boolean booleanValuePull) throws Exception {//

                                            //软键盘关闭
                                            KeyboardUtils.hideSoftInput(ChangePasswordActivity.this);

                                            //"password":"RTEwQURDMzk0OUJBNTlBQkJFNTZFMDU3RjIwRjg4M0U="
                                            //这个接口很奇怪，提示的数据是在message之中
                                            //{"data":"","message":"密码错误！","code":"20211"}
                                            //这个可能要放在新建一个listener
                                            //如果调用成功的格式是这样
//                                            {
//                                                    "code":"20000",
//                                                    "data":true,
//                                                    "message":"success"
//                                            }

                                            //CommUtils.displayToastShortCenter(response.succeed().getMessage());
                                            //{"data":"","message":"密码错误！","code":"20211"}

                                        }

                                        //自定义

                                    }, new ErrorConsumer() {

                                        @Override
                                        protected void error(ApiException e) {


                                        }
                                    });

                        }

                    }
                }));

        //对新密码的校验 应该放在点击提交的时候验证
        /*mCompositeDisposable.add(RxTextView.afterTextChangeEvents(etPasswordNew)
                .debounce(2000, java.util.concurrent.TimeUnit.MILLISECONDS)//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<TextViewAfterTextChangeEvent>() {
                    @Override
                    public void accept(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Exception {

                        String newPassWord = textViewAfterTextChangeEvent.getEditable().toString();

                        //做新密码的提示内容

                    }
                })
        );*/


    }

    /**
     * 对用户输入的新密码的校验
     */
    private boolean methodCheckNewPassrod(String newPassWord) {

        if (!TextUtils.isEmpty(newPassWord)) {

            //请输入新密码的时候 需要添加正则校验:数字 和 字母 8-20位
            //String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";
            //boolean result = RegexUtils.isMatch("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$", newPassWord);
            //LogUtils.d("itchen--->正则结果：" + result);

            //第一种简单提示
                            /*if (!result){
                                ToastUtils.setGravity(Gravity.CENTER,0,0);
                                ToastUtils.showLong("请输入：8-20位数字和字母~");
                            }*/

            //第二种复杂提示
            //if (!result) {

            //如果发现输入的密码不正确，那么就关闭弹窗仅仅为了让用户更好的看提示
            //KeyboardUtils.hideSoftInput(ChangePasswordActivity.this);

            //CommUtils.method_showAlertViewSingle(ChangePasswordActivity.this,//
            //        "提示", "新密码输入：8-20位数字和字母组合~", true);//
            //}

            return RegexUtils.isMatch("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$", newPassWord);

        }
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (etPasswordOld != null) {
            etPasswordOld.setText("");
        }

        if (etPasswordNew != null) {
            etPasswordNew.setText("");
        }

        if (etPasswordNewConfirm != null) {
            etPasswordNewConfirm.setText("");
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (etPasswordOld != null) {
            etPasswordOld.setText("");
            etPasswordOld = null;
        }

        if (etPasswordNew != null) {
            etPasswordNew.setText("");
            etPasswordNew = null;
        }

        if (etPasswordNewConfirm != null) {
            etPasswordNewConfirm.setText("");
            etPasswordNewConfirm = null;
        }

//        if (apiSubSonListener != null) {
//            apiSubSonListener = null;
//        }

        //重置该状态，避免反复登录或者其他原因到登录界面均是201401的标志内容。

//        if (keyboardWatcher != null) {
//            keyboardWatcher.removeSoftKeyboardStateListener(this);
//            keyboardWatcher = null;
//        }


    }

//    private void initListener() {
//
//        keyboardWatcher = new KeyboardWatcher(findViewById(Window.ID_ANDROID_CONTENT));
//        keyboardWatcher.addSoftKeyboardStateListener(this);
//
//        //文本的编辑内容 可以省略，然后是滚动视图的编辑内容
//        /*scrollView.setOnTouchListener(new View.OnTouchListener(){
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });*/
//
//    }

    @Override
    protected void gainDatas() {


    }

    @Override
    protected void methodBack() {

        ActivityUtils.finishActivity(ChangePasswordActivity.this);

    }

//    @Override
//    public void onSoftKeyboardOpened(int keyboardSize) {
//        //Log.e("wenzhihao", "----->show" + keyboardSize);
//        int[] location = new int[2];
//        bodyChange.getLocationOnScreen(location); //获取body在屏幕中的坐标,控件左上角
//        int x = location[0];
//        int y = location[1];
//        //Log.e("wenzhihao", "y = " + y + ",x=" + x);
//        int bottom = screenHeight - (y + bodyChange.getHeight());
//        //Log.e("wenzhihao", "bottom = " + bottom);
//        //Log.e("wenzhihao", "con-h = " + body.getHeight());
//
//        if (keyboardSize > bottom) {
//            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(bodyChange, "translationY", 0.0f, -(keyboardSize - bottom));
//            mAnimatorTranslateY.setDuration(300);
//            mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
//            mAnimatorTranslateY.start();
//            zoomIn(layoutImageLogoChange, keyboardSize - bottom);
//
//        }
//    }

//    @Override
//    public void onSoftKeyboardClosed() {
//        //Log.e("wenzhihao", "----->hide");
//        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(bodyChange, "translationY", bodyChange.getTranslationY(), 0);
//        mAnimatorTranslateY.setDuration(300);
//        mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
//        mAnimatorTranslateY.start();
//        zoomOut(layoutImageLogoChange);
//    }

    /**
     * 缩小
     *
     * @param view
     */
    public void zoomIn(final View view, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, scale);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, scale);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", 0.0f, -dist);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX).with(mAnimatorScaleY);

        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();

    }

    /**
     * f放大
     *
     * @param view
     */
    public void zoomOut(final View view) {

        if (view.getTranslationY() == 0) {
            return;
        }

        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();

        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", scale, 1.0f);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", scale, 1.0f);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", view.getTranslationY(), 0);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();

    }

}
